package org.madrox.core.controllers;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestOperations;

/**
 * 
 * @author gustavomoreira
 * 
 */
@Controller
@RequestMapping("/authTokenRequest")
public class AuthTokenRequestController {

	private RestOperations restOperations;

	private static final Logger LOGGER = Logger.getLogger("default");

	/**
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.GET)
	public String getState(HttpServletRequest request) {

		String token = UUID.randomUUID().toString();
		request.getSession().setAttribute("state", token);
		return token;
	}

	/**
	 * 
	 * @param idToken
	 *            the access token from the G+ Sign-in
	 * @param code
	 *            the code
	 * @param state
	 *            the state previously recovered
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST)
	public String doRequest(@RequestParam("access_token") String idToken,
			@RequestParam("code") String code,
			@RequestParam("state") String userState, HttpServletRequest request) {

		Object sessionState = request.getSession().getAttribute("state");
		if (sessionState == null) {
			LOGGER.log(Level.SEVERE, "State not found in session.");
			return "ERROR";
		}
		request.getSession().removeAttribute("state");
		String state = sessionState.toString();
		if (!state.equals(userState)) {

			LOGGER.log(Level.SEVERE,
					"State in session different from passed as argument.");
			return "ERROR2";
		}

		LinkedHashMap<String, String> requestMap = new LinkedHashMap<String, String>();
		requestMap.put("access_token", idToken);
		requestMap.put("code", code);
		requestMap
				.put("client_id",
						"509851416801-ac7tm0hhub28t5jd320s64j4f56oinfm.apps.googleusercontent.com");
		requestMap.put("client_secret", "JvF-6FZ4awblba3l8wiMopLc");

		return this.restOperations.postForObject(
				"https://www.googleapis.com/oauth2/v1/tokeninfo", requestMap,
				String.class);

	}

	/**
	 * @param restOperations
	 *            the generic interface to make requests
	 */
	@Qualifier("defaultRestTemplate")
	public void setRestOperations(RestOperations restOperations) {
		this.restOperations = restOperations;
	}

}
